/**
 * @author lulongwen
 * Date: 2023-09-13 22:31
 * Description: DeleteNode 删除节点
 */

import { useCallback } from 'react';
// import PropTypes from 'prop-types';
import ReactFlow, {
  Background,
  BackgroundVariant,
  useNodesState,
  useEdgesState,
  addEdge,
  getIncomers,
  getOutgoers,
  getConnectedEdges,
} from 'reactflow';
import type { Edge, Connection, Node } from 'reactflow';

import { initialNodes, initialEdges } from './nodes-edges';

DeleteNode.propTypes = {

};

function DeleteNode() {
  const [nodes, , onNodesChange] = useNodesState(initialNodes);
  const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);

  const onConnect = useCallback((params: Connection) => setEdges(addEdge(params, edges)), [edges]);

  // 删除节点
  const onNodesDelete = useCallback(
    (deleted: Node[]) => {
      // deleted 删除的那个节点
      const _edges = deleted.reduce((acc, node) => {
        // Node 入节点，别人链接我的节点，链接到当前的
        const incomers = getIncomers(node, nodes, edges);
        // Node 出节点，我链接别的节点
        const outgoers = getOutgoers(node, nodes, edges);

        // Edge 有链接关系的节点
        const connectedEdges = getConnectedEdges([node], edges);
        // Edge 剩下的没有链接关系的节点
        const remainingEdges = acc.filter((edge: Edge) => !connectedEdges.includes(edge));
        console.log({deleted, incomers, outgoers, connectedEdges, remainingEdges })

        const createdEdges = incomers.flatMap(({ id: source }) => {
          return outgoers.map(({ id: target }) => ({ id: `${source}->${target}`, source, target }))
        });

        return [...remainingEdges, ...createdEdges];
      }, edges);
      setEdges(_edges);
    },
    [nodes, edges]
  );

  return (
    <ReactFlow
      nodes={nodes}
      edges={edges}
      onNodesChange={onNodesChange}
      onNodesDelete={onNodesDelete}
      onEdgesChange={onEdgesChange}
      onConnect={onConnect}
      fitView
      attributionPosition="top-right"
    >
      <Background
        variant={BackgroundVariant.Dots}
        gap={12}
        size={1}
      />
    </ReactFlow>
  );
}

export default DeleteNode;
